<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>字符串执行</title>
</head>

<body>

    <script>
        // 请实现方法 parse ，作用如下：
        var object = {
            b: { c: 4 }, d: [{ e: 5 }, { e: 6 }]
        };

        console.log(parse(object, 'b.c') == 4) //true
        console.log(parse(object, 'd[0].e') == 5) //true
        console.log(parse(object, 'd.0.e') == 5) //true
        console.log(parse(object, 'd[1].e') == 6) //true
        console.log(parse(object, 'd.1.e') == 6) //true
        console.log(parse(object, 'f') == 'undefined') //true

        // function parse(obj, str) {
        //     var arr = str.replace(/\[(\w)\]/g, '.$1').split('.'), i = 0, tmp = obj;//把[]都替换成.的形式
        //     while (i < arr.length && tmp) {
        //         tmp = tmp[arr[i++]];
        //     }
        //     //console.log(tmp)
        //     return tmp || 'undefined';//注意undefined要返回字符串
        // }

        // function parse(obj, str) {
        //     str.replace('[', '.').replace(']', '').split('.').map((prop) => obj = obj[prop]);
        //     return obj || 'undefined';
        // }

        function parse(obj, str) {
            let arr = str.replace('[', '.').replace(']', '').split('.')
            // console.log(arr)
            let result = JSON.parse(JSON.stringify(obj))
            arr.forEach(prop => {
                result = result[prop]
            })
            return result || 'undefined'
        }

        console.log(object)
        let a = {}

    </script>



</body>

</html>